<?php

if (!class_exists("PST_FILEUPLOAD")) {

    class PST_FILEUPLOAD extends PST_PRESENTATION {

        public function __construct($settings) {
            parent::__construct($settings);

            if (empty($this->array['type'])) {
                $this->array['type'] = "file";
            }
        }

        public function saveDbQuery() {
            global $MODEL;

            if (isset($this->name) && isset($this->value) && is_array($this->value)) {
                // Obtengo la info del archivo
                $file = pathinfo($this->value['name']);
                $name = $file['filename'];
                $type = $this->value['type'];
                $size = $this->value['size'];
                $tmp_file = $this->value['tmp_name'];

                // Carpeta base del storage
                $folder = "files/";

                $filename = md5($file['filename'] . time()) . "." . $file['extension'];

                // Agrego 5 subniveles por el archivo
                $subpath = "";
                for ($j = 0; $j < 5; $j++) {
                    $subpath.= substr($filename, ($j * 2), 2) . "/";
                }

                // Creo la carpeta si no existe
                $path = WWW_ROOT . $folder;
                foreach (explode('/', $subpath) as $dirPart) {
                    $path.= $dirPart . "/";
                    if (!is_dir($path)) {
                        mkdir($path);
                    }
                }

                $final = WWW_ROOT . $folder . $subpath . $filename;

                if (move_uploaded_file($tmp_file, $final)) {
                    $MODEL->Query("INSERT INTO files (filename, name, type, size)
                                   VALUES ('" . $filename . "', '" . $name . "', '" . $type . "', " . $size . ")");

                    return WWW . $folder . $subpath . $filename;
                }
            }

            return "";
        }

    }

}
